package controller

import (
	"illuminant/config"
	"illuminant/logger"
	"illuminant/service"
	"illuminant/util"
	"io"
	"os"
	"path"
	"path/filepath"

	"gitee.com/wangyubin/gutils"

	"github.com/gin-gonic/gin"
	uuid "github.com/satori/go.uuid"
)

func UploadFile(c *gin.Context) {
	lg := logger.GetLogger()
	file, header, err := c.Request.FormFile("file")
	if err != nil {
		util.Fail(c, util.UPLOAD_ERROR, "param error: "+err.Error(), nil)
		lg.Err(err)
		return
	}
	lg.Debug().Msgf("file: %v", file)
	fileType := c.Param("type")
	if fileType == "" {
		util.Fail(c, util.UPLOAD_ERROR, "param error: 没有指定 file type", nil)
		lg.Err(err)
		return
	}
	// 创建上传用的文件夹
	cnf := config.Get()
	fileDir := path.Join(cnf.File.UploadDir, fileType)
	if err = gutils.CreateDir(fileDir); err != nil {
		util.Fail(c, util.UPLOAD_ERROR, "create upload dir error: "+err.Error(), nil)
		return
	}

	fileName := header.Filename
	fid := uuid.NewV4().String()
	filePath := path.Join(fileDir, fid+filepath.Ext(fileName))
	out, _ := os.Create(filePath)
	defer out.Close()
	_, err = io.Copy(out, file)
	if err != nil {
		util.Fail(c, util.UPLOAD_ERROR, err.Error(), nil)
		return
	}

	// add file info to db
	if err = service.AddFile(fid, fileName, filePath); err != nil {
		util.Fail(c, util.UPLOAD_ERROR, err.Error(), nil)
		return
	}

	util.Success(c, "upload success", map[string]string{"fid": fid})
}

func DeleteFile(c *gin.Context) {
	fileId := c.Param("fileId")
	file, err := service.DeleteFileByID(fileId)
	if err != nil {
		util.Fail(c, util.DATA_DELETE_ERROR, err.Error(), nil)
		return
	}

	// delete file from disk
	os.Remove(file.Filepath)

	util.Success(c, "delete success", map[string]string{"fid": fileId})
}

func RefreshFileStatus(c *gin.Context) {
	fileId := c.Param("fileId")
	file, err := service.GetFileByID(fileId)
	if err != nil {
		util.Fail(c, util.DATA_SEARCH_ERROR, err.Error(), nil)
		return
	}

	if gutils.FileIsExisted(file.Filepath) && file.Status != 1 {
		file, err = service.RefreshFileStatusByID(file.ID, 1)
	}

	if !gutils.FileIsExisted(file.Filepath) && file.Status != 0 {
		file, err = service.RefreshFileStatusByID(file.ID, 0)
	}

	util.Success(c, "refresh success", map[string]string{"fid": fileId})
}
